<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<meta name="apple-mobile-web-app-capable" content="yes">
		<meta name="apple-mobile-web-app-status-bar-style" content="black">
		<meta name="format-detection" content="telephone=no,email=no" />
		<title>订单列表</title>
		<link href="css/mui.min.css" rel="stylesheet" />
		<link href="css/style.css" rel="stylesheet" />
	</head>
	<body>
		<header class="mui-bar mui-bar-nav">
			<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
			<h1 class="mui-title">订单列表</h1>
		</header>
		
		<div id="pullrefresh" class="mui-content mui-scroll-wrapper transparent">
			<div class="mui-scroll">
				<div id="orderList">
				</div>
			</div>
		</div>
		<div id="dcontent" class="dcontent"></div>
		<script src="js/mui.min.js"></script>
		<script src="js/delayimg.min.js"></script>
		<script src="js/app.js"></script>
		<script>
			var isnodata = false,
				page = 1,
				orderStatus,
				payOrderId,
				parentElem,
				pays={},
				mask=null,
				title=document.getElementsByClassName('mui-title')[0],
				loadPage;
			mui.init({
				beforeback:function(){
					mui.fire(plus.webview.getWebviewById('user/usercenter.html'),'updateData');
				},
				pullRefresh : {
				    container:'#pullrefresh',
				    deceleration:0.0006,
				     down : {
						contentdown : "下拉可以刷新",
						contentover : "释放立即刷新",
						contentrefresh : "正在刷新...",
						callback :function(){
							setTimeout(function(){
								reloadPage(orderStatus);
								mui('#pullrefresh').pullRefresh().endPulldownToRefresh();
							},2000)
						}
				    },
				    up : {
					    contentrefresh : "正在加载...",
					    contentnomore:'已加载完订单',
					    callback :function(){
					      	var self=this;
					      	if (!isnodata) {
					      		page++;
						        mui.ajax(URL+'api/MemberOrder/GetOrders?orderStatus='+orderStatus+'&pageNo='+page+'&pageSize=10',{
									dataType:'json',
									type:'get',
									timeout:10000,
									success:function(data){
										if(data.Success=='true'){
						                    var html='';
									        if(data.Orders.length > 0) {
									        	for(var i=0;i<data.Orders.length;i++){
										            html+='<div class="order-info " data-id="'+data.Orders[i].id+'">'+
														'<div class="item">'+
															'<div class="order-shop">'+
																'<a class="vshop-url" data-id="'+data.Orders[i].vshopId+'">'+data.Orders[i].shopname+'</a>'+
															'<span class="mui-pull-right">'+data.Orders[i].status+'</span></div>'+
														'</div>';
										            	for(var j=0;j<data.Orders[i].itemInfo.length;j++){
											                html+='<div class="item productlist">'+
											                    '<div class="buy-goods clearfix">'+
											                        '<a class="goods-url goods-img" data-id="'+data.Orders[i].itemInfo[j].productId+'" data-itemid="'+data.Orders[i].itemInfo[j].id+'"><img src="'+data.Orders[i].itemInfo[j].image+'"/></a>'+
											                        '<p><em>¥ '+data.Orders[i].itemInfo[j].price+'</em><span><a class="goods-url" data-id="'+data.Orders[i].itemInfo[j].productId+'">'+data.Orders[i].itemInfo[j].productName+'</a></span></p>'+
											                        '<h5><span>x '+data.Orders[i].itemInfo[j].count+'</span>';
											                        	if(data.Orders[i].itemInfo[j].size!='')
																			html += '尺寸：'+data.Orders[i].itemInfo[j].size+'&nbsp;&nbsp;';
																		if(data.Orders[i].itemInfo[j].color!='')
																			html += '颜色：'+data.Orders[i].itemInfo[j].color+'&nbsp;&nbsp;';
																		if(data.Orders[i].itemInfo[j].version!='')
																			html += '规格：'+data.Orders[i].itemInfo[j].version;
											                            html+='</h5>'+
											                    '</div>'+
											                '</div>';
										               	}
											            html+='<div class="item">'+
											            	'<div class="item-text">'+
										                    '&nbsp;<span class="mui-pull-right order-total">共'+data.Orders[i].productCount+'件商品 &nbsp;&nbsp; 总价：<em>¥ '+data.Orders[i].orderTotalAmount+'</em></span>'+
											            	'</div>'+
											            '</div>';
											            if(data.Orders[i].orderStatus==1){
											            	html+='<div class="item total-m item-btn">'+
											            		'<button class="mui-btn cancelOrder">取消订单</button>'+
											            		'<button class="mui-btn mui-btn-negative payOrder">付款</button>'+
											            		'<button class="mui-btn showOrder">查看订单</button>'+
											            	'</div>';
											            }
											             if(data.Orders[i].orderStatus==2){
												            	html+='<div class="item total-m item-btn">'+
												            		'<button class="mui-btn orderRefund">退货/退款</button>'+
												            		'<button class="mui-btn showOrder">查看订单</button>'+
												            	'</div>';
												            }
											            if(data.Orders[i].orderStatus==3){
											            	html+='<div class="item total-m item-btn">'+
											            		'<button class="mui-btn mui-btn-negative enterOrder">确认收货</button>'+
											            		'<button class="mui-btn orderRefund">退货/退款</button>'+
											            		'<button class="mui-btn showOrder">查看订单</button>'+
											            	'</div>';
											            }
											            if(data.Orders[i].orderStatus==5){
											            	if(data.Orders[i].commentCount==0){
												            	html+='<div class="item total-m item-btn">'+
												            		'<button class="mui-btn mui-btn-negative evaluateOrder">评价</button>'+
												            		'<button class="mui-btn showOrder">查看订单</button>'+
												            	'</div>';
											            	}else{
											            		html+='<div class="item total-m item-btn">'+
												            		'<button class="mui-btn showOrder">查看订单</button>'+
												            	'</div>';
											            	}
											            }
											            
											        html+='</div>';
										       	}
									        	document.getElementById('orderList').insertAdjacentHTML('beforeend',html);
									        	delayimg.render();
									        }else{
												isnodata = true;
											}
						                    //if (orderTotal<=page*10) {isnodata = true;}
											self.endPullupToRefresh(isnodata);
					      					
										}
									},
									error:function(xhr,type,errorThrown){
										plus.nativeUI.toast('请求失败，请检查网络')
									}
								});
						    }else{
						    		self.endPullupToRefresh(isnodata);
						    }
				    	}
				    }
				},
				swipeBack: true
			});
			
			if (mui.os.android)
				document.getElementsByClassName('mui-scroll')[0].className='';
			
			mui.plusReady(function() {

				orderStatus=plus.webview.currentWebview().orderStatus;
				if(orderStatus==0){
	            	title.innerText='全部订单';
	            }else if(orderStatus==1)
	            	title.innerText='待付款订单';
	            	else if(orderStatus==2)
	            	title.innerText='待发货订单';
	            else if(orderStatus==3)
	            	title.innerText='待收货订单';
	            else if(orderStatus==5)
	            	title.innerText='待评价订单';
//	            	else if(orderStatus==6)
//	            	title.innerText='退换/退货';
				plus.webview.currentWebview().setStyle({scrollIndicator:'none'});
				
				loadPage=function(orderStatus){
					var w=plus.nativeUI.showWaiting('',{padlock:true});
					mui.ajax(URL+'api/MemberOrder/GetOrders?orderStatus='+orderStatus+'&pageNo=1&pageSize=10',{
						dataType:'json',
						type:'get',
						timeout:10000,
						success:function(data){
							console.log(data)
							if(data.Success=='true'){
								var html='';
						        if(data.Orders.length > 0) {
						        	for(var i=0;i<data.Orders.length;i++){
							            html+='<div class="order-info " data-id="'+data.Orders[i].id+'">'+
											'<div class="item">'+
												'<div class="order-shop">'+
												'<a class="vshop-url" data-id="'+data.Orders[i].vshopId+'">'+data.Orders[i].shopname+'</a>'+
												'<span class="mui-pull-right">'+data.Orders[i].status+'</span></div>'+
											'</div>';
							            	for(var j=0;j<data.Orders[i].itemInfo.length;j++){
								                html+='<div class="item productlist">'+
								                    '<div class="buy-goods clearfix">'+
								                        '<a class="goods-url goods-img" data-id="'+data.Orders[i].itemInfo[j].productId+'" data-itemid="'+data.Orders[i].itemInfo[j].id+'"><img src="'+data.Orders[i].itemInfo[j].image+'"/></a>'+
								                        '<p><em>¥ '+data.Orders[i].itemInfo[j].price+'</em><span><a class="goods-url" data-id="'+data.Orders[i].itemInfo[j].productId+'">'+data.Orders[i].itemInfo[j].productName+'</a></span></p>'+
								                        '<h5><span>x '+data.Orders[i].itemInfo[j].count+'</span>';
								                        	if(data.Orders[i].itemInfo[j].size!='')
																html += '尺寸：'+data.Orders[i].itemInfo[j].size+'&nbsp;&nbsp;';
															if(data.Orders[i].itemInfo[j].color!='')
																html += '颜色：'+data.Orders[i].itemInfo[j].color+'&nbsp;&nbsp;';
															if(data.Orders[i].itemInfo[j].version!='')
																html += '规格：'+data.Orders[i].itemInfo[j].version;
								                            html+='</h5>'+
								                    '</div>'+
								                '</div>';
							               	}
								            html+='<div class="item">'+
								            	'<div class="item-text">'+
							                    '&nbsp;<span class="mui-pull-right order-total">共'+data.Orders[i].productCount+'件商品 &nbsp;&nbsp; 总价：<em>¥ '+data.Orders[i].orderTotalAmount+'</em></span>'+
								            	'</div>'+
								            '</div>';
								            if(data.Orders[i].orderStatus==1){
									            	html+='<div class="item total-m item-btn" data-amout="'+data.Orders[i].orderTotalAmount+'">'+
									            		'<button class="mui-btn cancelOrder">取消订单</button>'+
									            		'<button class="mui-btn mui-btn-negative payOrder">付款</button>'+
									            		'<button class="mui-btn showOrder">查看订单</button>'+
									            	'</div>';
								            }
								            if(data.Orders[i].orderStatus==2){
								            	html+='<div class="item total-m item-btn">'+
								            		'<button class="mui-btn orderRefund">退货/退款</button>'+
								            		'<button class="mui-btn showOrder">查看订单</button>'+
								            	'</div>';
								            }
								            if(data.Orders[i].orderStatus==3){
								            	html+='<div class="item total-m item-btn">'+
								            		'<button class="mui-btn mui-btn-negative enterOrder">确认收货</button>'+
								            		'<button class="mui-btn orderRefund">退货/退款</button>'+
								            		'<button class="mui-btn showOrder">查看订单</button>'+
								            	'</div>';
								            }
								            if(data.Orders[i].orderStatus==5){
									            	if(data.Orders[i].commentCount==0){
										            	html+='<div class="item total-m item-btn">'+
										            		'<button class="mui-btn mui-btn-negative evaluateOrder">评价</button>'+
										            		'<button class="mui-btn showOrder">查看订单</button>'+
										            	'</div>';
									            	}else{
									            		html+='<div class="item total-m item-btn">'+
										            		'<button class="mui-btn showOrder">查看订单</button>'+
										            	'</div>';
									            	}
								            }
								            
								        html+='</div>';
							       	}
						            document.getElementById('orderList').innerHTML=html;
						            delayimg.init();
						        }else{
							        	html+='<div class="empty-show"><h4>暂无此类订单...</h4><button id="closeWv" class="mui-btn mui-btn-negative">去其他地方逛逛</button></div>';
							        	document.getElementById('pullrefresh').innerHTML=html;
						        }
						        
								w.close();
								document.getElementById('pullrefresh').className='mui-content mui-scroll-wrapper';
							}
						},
						error:function(xhr,type,errorThrown){
//							console.log(JSON.stringify(xhr))
							w.close();
							reloadWvLoad();
						}
					});
				}

				loadPage(orderStatus);
				
				plus.payment.getChannels(function(channels){
					var content=document.getElementById('dcontent');
					for(var i in channels){
						var channel=channels[i];
						if(channel.id=='alipay' /*|| channel.id=='wxpay'*/){
							pays[channel.id]=channel;
							var de=document.createElement('div');
							de.setAttribute('class','custom-btn');
							de.setAttribute('onclick','pay(this.id)');
							de.id=channel.id;
							de.innerText=channel.description+"支付";
							content.appendChild(de);
							checkServices(channel);
						}
					}
				},function(e){
					plus.nativeUI.alert("获取支付方式失败："+e.message);
				});
				
			});
			
			function reloadPage(orderStatus){
				loadPage(orderStatus);
				isnodata = false;
				page = 1;
				mui('#pullrefresh').pullRefresh().refresh(true);
			}
			
			document.addEventListener('updateData', function() {
//						w=plus.nativeUI.showWaiting('',{padlock:true});
					document.getElementById('orderList').innerHTML="";
				reloadPage(orderStatus);
			});
			
			
			mui('#orderList').on('tap', '.vshop-url', function() {
				var vshopid = this.getAttribute('data-id');
				if(vshopid==null){
					plus.nativeUI.toast('该店铺暂未开通微店')
				}else{
					showVshop(vshopid,'/')
				}
			});
			
			mui('#orderList').on('tap', '.goods-url', function() {
				var id = this.getAttribute('data-id');
				showProduct(id);
			});
			
			mui('#orderList').on('tap', '.showOrder', function() {
				var orderId = this.parentNode.parentNode.getAttribute('data-id');
				mui.openWindow({
					id:'order-detail.html',
					url:'order-detail.html',
					extras:{
						orderId:orderId
				    },
					show: {
						autoShow:true,
						aniShow: 'pop-in'
					},
					waiting: {
						autoShow: false
					}
				});
			});
			
			mui('#orderList').on('tap', '.enterOrder', function() {
				var orderId = this.parentNode.parentNode.getAttribute('data-id'),
					btnArray = ['取消', '确认'];
				mui.confirm('请确保您已收到宝贝,再收货！', '', btnArray, function(e) {
					if (e.index == 1) {
				    	mui.ajax(URL+'api/MemberOrder/PostConfirmOrder',{
							data:JSON.stringify({orderId:orderId}),
							dataType:'json',
							type:'POST',
							contentType:'application/json',
							timeout:10000,
							success:function(data){
								if(data.Success=="true"){
									plus.nativeUI.toast('已确认收货');
									reloadPage(orderStatus);
								}else{
									plus.nativeUI.toast('确认收货失败，请稍后重试')
								}
							},
							error:function(xhr,type,errorThrown){
								plus.nativeUI.toast('请求失败，请检查网络')
							}
						});
					}
				});
			});
			//评价页面
			mui('#orderList').on('tap','.evaluateOrder',function(){
				var _orderId=this.parentNode.parentNode.getAttribute("data-id")
				if(app.isLogin()){
					mui.openWindow({
						id:'comment-submit.html',
						url:'comment-submit.html',
						extras:{
							orderId:_orderId
					    },
						show: {
							autoShow:true,
							aniShow: 'pop-in'
						},
						waiting: {
							autoShow: false
						}
					});
				}else{
					showLogin('/');
				}
			})
			//退单
			mui('#orderList').on('tap','.orderRefund',function(){
							var _orderId=this.parentNode.parentNode.getAttribute("data-id");
							var _itemid=this.parentNode.parentNode.getElementsByClassName("productlist")[0].getElementsByClassName("buy-goods")[0].getElementsByClassName("goods-url")[0].getAttribute("data-itemid");

							if(app.isLogin()){
								mui.openWindow({
									id:'order-refund.html',
									url:'order-refund.html',
									extras:{
										orderId:_orderId,
										itemid:_itemid,
										orderStatus:orderStatus
								    },
									show: {
										autoShow:true,
										aniShow: 'pop-in'
									},
									waiting: {
										autoShow: false
									}
								});
							}else{
								showLogin('/');
							}
						})
			mui('#orderList').on('tap', '.cancelOrder', function() {
				var orderId = this.parentNode.parentNode.getAttribute('data-id'),
					btnArray = ['取消', '确认'];
				mui.confirm('确定取消该订单？', '', btnArray, function(e) {
					if (e.index == 1) {
				    	mui.ajax(URL+'api/MemberOrder/PostCloseOrder',{
							data:JSON.stringify({orderId:orderId}),
							dataType:'json',
							type:'POST',
							contentType:'application/json',
							timeout:10000,
							success:function(data){
								if(data.Success=="true"){
									plus.nativeUI.toast('订单取消成功');
									reloadPage(orderStatus);
								}else{
									plus.nativeUI.toast('订单取消失败，请稍后重试')
								}
							},
							error:function(xhr,type,errorThrown){
								plus.nativeUI.toast('订单取消失败，请检查网络')
							}
						});
					}
				});
			});
			mui('#orderList').on('tap', '.payOrder', function() {
				payOrderId = this.parentNode.parentNode.getAttribute('data-id');
				if(this.parentNode.getAttribute('data-amout')<=0){
					var pW=plus.nativeUI.showWaiting();
					mui.ajax(URL+'api/Order/GetPayOrderByIntegral?orderIds='+payOrderId,{
						dataType:'json',
						type:'get',
						timeout:10000,
						success:function(data){
							pW.close();
							if(data.Success=="true"){
								plus.nativeUI.alert('订单需支付金额为零，购买成功，等待发货');
								reloadPage(orderStatus);
							}else{
								plus.nativeUI.toast('订单支付失败，请稍后重试')
							}
						},
						error:function(xhr,type,errorThrown){
							pW.close();
							plus.nativeUI.toast('订单支付失败，请检查网络')
						}
					});
					
				}else{
					if(!mask)
						mask = mui.createMask(function(){document.getElementById('dcontent').className='dcontent';});
					mask.show();
					document.getElementById('dcontent').className='dcontent active';
				}
			});
			//更新
//			document.addEventListener('updateData', function() {
//						if(app.isLogin()){
//							document.getElementById('orderList').innerHTML="";
//							loadPage(orderStatus);
//						}
//						
//					});
			
			
			// 检测是否安装支付服务
			function checkServices(pc){
				if(!pc.serviceReady){
					var txt=null;
					switch(pc.id){
						case "alipay":
						txt="检测到系统未安装“支付宝快捷支付服务”，无法完成支付操作，是否立即安装？";
						break;
						default:
						txt="系统未安装“"+pc.description+"”服务，无法完成支付，是否立即安装？";
						break;
					}
					plus.nativeUI.confirm(txt,function(e){
						if(e.index==0){
							pc.installService();
						}
					},pc.description);
				}
			}
			
			var wPay=null;
			var PAYSERVER=URL+'api/payment/GetPaymentList?orderIds=';
			// 支付
			function pay(id){
				if(wPay){return;}//检查是否请求订单中
				//var url=PAYSERVER;
				if(id=='alipay'||id=='wxpay'){
					//url+=id;
				}else{
					plus.nativeUI.alert("不支持此支付通道！");
					return;
				}
				wPay=plus.nativeUI.showWaiting();
				
				// 请求支付订单
				var xhr=new XMLHttpRequest();
				xhr.onreadystatechange=function(){
					switch(xhr.readyState){
						case 4:
						wPay.close();wPay=null;
						if(xhr.status==200){
							var order=JSON.parse(xhr.responseText);
//							console.log(order)
							plus.payment.request(pays[id],order[0].url,function(result){
								plus.nativeUI.alert("支付成功，等待卖家发货！",function(){
									mask.close();
									document.getElementById('dcontent').className='dcontent';
									reloadPage(orderStatus);
								});
							},function(e){
								mask.close();
								document.getElementById('dcontent').className='dcontent';
								plus.nativeUI.alert("订单支付失败，请重新支付！");
							});
						}else{
							plus.nativeUI.alert("获取订单信息失败！");
						}
						break;
						default:
						break;
					}
				}
				console.log('GET',PAYSERVER+payOrderId)
				xhr.open('GET',PAYSERVER+payOrderId);
				xhr.send();
			}
		</script>
	</body>

</html>